﻿using B.S.BasicData.Infrastructure.Implement;
using B.S.BasicData.Infrastructure.Interface;
using Common;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;

namespace B.S.BasicData.Api.Write.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static  IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            services.AddAutoMapper(typeof(MyMapper));
            services.AddScoped<JwtTools>();
            return services;
        }

        public static IServiceCollection AddDbContextServices<MyDbContext>(this IServiceCollection services, string? connectionString,bool enableSqlLog) where MyDbContext : DbContext 
        {
            return services.AddDbContext<MyDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                        );
                });
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((categroy, level) => categroy == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
                    }));
                }
            });
        }
        public static void AddJWT(this IServiceCollection collection,WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    ValidateLifetime = true,
                    IssuerSigningKey=new SymmetricSecurityKey(secretByte)
                };
            });
        }


    }
}
